# -*- coding: utf-8 -*-
"""
@author: luhx
@file: breed_range.py
@time: 2023/7/28 11:09
@desc:
"""
import copy
from datetime import datetime, timedelta
from kds_util.mysql_database import PyMySql
from highlow.envs import Envs


class BreedRange:
    arr_total = {}
    period_range = {}

    @classmethod
    def init(cls):
        cls.arr_total = cls.get_breed_range()
        for i in [5, 15, 30, 60, 120]:
            cls.period_range[i] = cls.calc_period_range(i)

    @classmethod
    def get_breed_range(cls):
        """获取所有品种白盘，夜盘时间周期"""
        arr = {}
        sql = "SELECT * from tbl_future_tx_time_range"
        mysql = PyMySql(f'mysql+pymysql://root:{Envs.dest_mysql_passwd}@{Envs.dest_ip}:3306/hqdb?charset=utf8', cursor=True)
        items = mysql.query(sql)
        for item in items:
            breed = item['breed']
            # if breed != 'SA':
            #     continue
            rangelist = item['rangelist']
            arr[breed] = eval(rangelist)
        return arr

    @classmethod
    def calc_period_range(cls, period=30):
        breed_dic = {}
        t = datetime.now()
        for breed in cls.arr_total.keys():
            breed_dic[breed] = {}
            range_arr = cls.arr_total[breed]
            dt_arr = cls.get_dt_arr(range_arr, t)
            one_minutes = cls.get_period_dt_arr(dt_arr, period)
            for period_dt in one_minutes:
                for dt in period_dt:
                    breed_dic[breed][dt.hour * 10000 + dt.minute*100] = period_dt[-1].hour * 10000 + period_dt[-1].minute*100
        return breed_dic

    @classmethod
    def get_period_dt_arr(cls, dt_arr, period):
        """获取若干分钟为周期的时间序列，得出的为二维数组a[][],
        其中a[0]表示第1个周期内的1分钟时间序列，依此类推"""
        one_minutes = []
        per_dt = []
        for dt1 in dt_arr:
            start = dt1[0]
            end = dt1[1]
            while start <= end:
                per_dt.append(start)
                if len(per_dt) >= period or start == dt_arr[-1][-1]:
                    one_minutes.append(copy.copy(per_dt))
                    per_dt.clear()
                start += timedelta(minutes=1)
        return one_minutes

    @classmethod
    def get_dt_arr(cls, range_arr, t):
        """获取排序好的由小到大的时间序列"""
        dt_arr = []
        for r in range_arr:
            start = r[0]
            end = r[1]
            dt1 = t.replace(hour=start // 100, minute=start % 100, second=0, microsecond=0)
            dt2 = t.replace(hour=end // 100, minute=end % 100, second=0, microsecond=0)
            if start > end:
                dt2 = dt2 + timedelta(days=1)
            if 300 < start < 2100:
                dt1 = dt1 + timedelta(days=1)  # 白盘先加一天
                dt2 = dt2 + timedelta(days=1)
            dt_arr.append([dt1, dt2])
            dt_arr = sorted(dt_arr, key=lambda x: x[0])
        return dt_arr


if __name__ == '__main__':
    BreedRange.init()
    print("work end.")
